/**
 * 
 */
package org.youisoft.summer.evaluator.registry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;




/**
 * @author zijiang.jl
 *
 */
public abstract class AbstractRegistry implements Registry{
	private Log logger=LogFactory.getLog(Registry.class);
	private static final java.util.Map<String, Object> components=new java.util.concurrent.ConcurrentHashMap<String, Object>();
	private static final java.util.Map<Class<?>, Class<?>> classes=new java.util.concurrent.ConcurrentHashMap<Class<?>, Class<?>>();
	private static final java.util.Map<String, String> aliasMaps=new java.util.concurrent.ConcurrentHashMap<String, String>();

	@Override
	public void registerAlias(String cName, String... alias) {
		if(alias!=null){
			if(this.find(cName)!=null){
				for(String a:alias){
					if(a!=null) aliasMaps.put(a, cName);
				}
			}
		}
		
	}
	
	@Override
	public void register(Class<?> clazz) {
		if(clazz.getAnnotation(org.youisoft.summer.evaluator.annotation.Component.class)!=null) 
			classes.put(clazz, clazz);
		
		logger.error("Class is not a component!"+clazz.getName());
	}
	
	

	@Override
	public void unRegister(String cName) {
		components.remove(cName);
		aliasMaps.remove(cName);
	}

	
	
	
	@Override
	public Object find(String name) {
		if(name==null) return null;
		Object obj=components.get(name);
		if(obj!=null) return obj;
		return find(aliasMaps.get(name));
	}

	@Override
	public <C> C find(String cName,Class<C> expected) {
		Object obj=this.find(cName);
		if(expected.isAssignableFrom(obj.getClass())){
			return expected.cast(obj);
		}
		return null;
	}

	@Override
	public void register(Object object) {
		org.youisoft.summer.evaluator.annotation.Component com=object.getClass().getAnnotation(org.youisoft.summer.evaluator.annotation.Component.class);
		if(com!=null){
			if(com.name()==null) {
				logger.error("the name of component is null! ");
				return;
			}
			components.put(com.name(), object);
			this.registerAlias(com.name(), com.alias());
		}else{
			logger.warn("Component missing:"+object.getClass().getName());
		}
	}

	@Override
	public void register(String name, Object object) {
		org.youisoft.summer.evaluator.annotation.Component com=object.getClass().getAnnotation(org.youisoft.summer.evaluator.annotation.Component.class);
		if(com!=null){
			if(com.name()==null) {
				logger.error("the name of component is null! ");
				return;
			}
			components.put(com.name(), object);
			if(!name.equals(com.name())) this.registerAlias(name, com.name());
		}else{
			logger.warn("Component missing:"+object.getClass().getName());
		}
		
	}

}
